<template>
  <div class="scale-questions">
    <div class="page-header">
      <div class="scale-info">
        <h3>{{ scale.name }}</h3>
        <el-tag>{{ scale.type }}</el-tag>
        <div class="score-info">
          <span>量表总分: {{ scale.totalScore }}</span>
          <span>当前题目总分: {{ currentTotalScore }}</span>
        </div>
      </div>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加题目
      </el-button>
    </div>

    <!-- 题目列表 -->
    <el-table
      v-loading="loading"
      :data="questionList"
      border
      row-key="id"
      :default-sort="{ prop: 'orderNum', order: 'ascending' }"
    >
      <el-table-column prop="orderNum" label="序号" width="80" sortable />
      <el-table-column prop="content" label="题目内容" show-overflow-tooltip />
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getQuestionTypeTag(row.type)">
            {{ getQuestionTypeLabel(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="dimension" label="维度" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="success" link @click="handlePreview(row)">
            预览
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 题目表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加题目' : '编辑题目'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="题目内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="题目类型" prop="type">
          <el-select v-model="form.type" style="width: 100%">
            <el-option label="单选题" value="SINGLE" />
            <el-option label="多选题" value="MULTIPLE" />
            <el-option label="文本题" value="TEXT" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目分数" prop="score">
          <el-input-number v-model="form.score" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="排序号" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="1" />
        </el-form-item>
        <el-form-item label="选项" prop="options">
          <div v-for="(option, index) in form.options" :key="index" class="option-item">
            <el-input v-model="option.content" placeholder="选项内容">
              <template #append>
                <el-input-number 
                  v-model="option.score" 
                  :min="0" 
                  :max="form.score || 0"
                  placeholder="分值"
                />
              </template>
            </el-input>
            <el-button type="danger" link @click="removeOption(index)">
              删除
            </el-button>
          </div>
          <el-button type="primary" link @click="addOption">
            添加选项
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 题目预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="题目预览"
      width="600px"
    >
      <div class="question-preview">
        <h4>{{ previewQuestion.content }}</h4>
        <div class="options">
          <template v-if="previewQuestion.type === 'SCALE'">
            <el-radio-group v-model="previewAnswer">
              <el-radio 
                v-for="option in previewQuestion.options" 
                :key="option.id" 
                :label="option.score"
              >
                {{ option.content }}
              </el-radio>
            </el-radio-group>
          </template>
          <template v-else-if="previewQuestion.type === 'SINGLE'">
            <el-radio-group v-model="previewAnswer">
              <el-radio 
                v-for="option in previewQuestion.options" 
                :key="option.id" 
                :label="option.id"
              >
                {{ option.content }}
              </el-radio>
            </el-radio-group>
          </template>
          <template v-else>
            <el-checkbox-group v-model="previewAnswers">
              <el-checkbox 
                v-for="option in previewQuestion.options" 
                :key="option.id" 
                :label="option.id"
              >
                {{ option.content }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '../../../utils/request'

const route = useRoute()
const scaleId = route.params.id
const loading = ref(false)
const scale = ref({})
const questionList = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const previewVisible = ref(false)
const formRef = ref(null)

// 表单数据
const form = ref({
  content: '',
  type: 'SINGLE',
  score: 1,
  orderNum: 1,
  options: []
})

// 预览数据
const previewQuestion = ref({})
const previewAnswer = ref('')
const previewAnswers = ref([])

// 表单验证规则
const rules = {
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入题目分数', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
  options: [
    { 
      validator: (rule, value, callback) => {
        if (form.value.type !== 'TEXT' && (!value || value.length === 0)) {
          callback(new Error('请至少添加一个选项'))
        } else if (form.value.type !== 'TEXT') {
          // 检查选项分数
          if (form.value.type === 'SINGLE') {
            // 单选题：检查每个选项的分数是否超过题目分数
            const invalidOption = value.find(opt => (opt.score || 0) > form.value.score)
            if (invalidOption) {
              callback(new Error('单选题每个选项的分数不能超过题目分数'))
            } else {
              callback()
            }
          } else if (form.value.type === 'MULTIPLE') {
            // 多选题：检查选项分数总和是否超过题目分数
            const totalOptionScore = value.reduce((sum, opt) => sum + (opt.score || 0), 0)
            if (totalOptionScore > form.value.score) {
              callback(new Error('多选题选项分数之和不能超过题目分数'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 计算当前题目总分
const currentTotalScore = computed(() => {
  return questionList.value.reduce((total, question) => {
    return total + (question.score || 0)
  }, 0)
})

// 获取量表详情
const fetchScale = async () => {
  try {
    const res = await request.get(`/admin/scales/one/${scaleId}`)
    if (res.code === 200) {
      scale.value = res.data
    } else {
      ElMessage.error(res.message || '获取量表信息失败')
    }
  } catch (error) {
    ElMessage.error('获取量表信息失败')
  }
}

// 获取题目列表
const fetchQuestions = async () => {
  loading.value = true
  try {
    const res = await request.get('/admin/questions', {
      params: {
        page: 1,
        size: 100,
        scaleId: scaleId,
        query: ''
      }
    })
    if (res.code === 200) {
      // 确保每个题目都有 options 属性
      questionList.value = res.data.records.map(question => ({
        ...question,
        options: question.options || []
      }))
    } else {
      ElMessage.error(res.message || '获取题目列表失败')
    }
  } catch (error) {
    console.error('获取题目列表错误:', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 添加选项
const addOption = () => {
  form.value.options.push({
    content: '',
    score: 0
  })
}

// 删除选项
const removeOption = (index) => {
  form.value.options.splice(index, 1)
}

// 获取题目类型标签样式
const getQuestionTypeTag = (type) => {
  const types = {
    SINGLE: '',
    MULTIPLE: 'success',
    SCALE: 'warning'
  }
  return types[type] || ''
}

// 获取题目类型标签文本
const getQuestionTypeLabel = (type) => {
  const labels = {
    SINGLE: '单选题',
    MULTIPLE: '多选题',
    SCALE: '量表题'
  }
  return labels[type] || type
}

// 处理添加题目
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    content: '',
    type: 'SINGLE',
    score: 1,
    orderNum: questionList.value.length + 1,
    options: []
  }
  dialogVisible.value = true
}

// 处理编辑题目
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// 处理预览题目
const handlePreview = (row) => {
  previewQuestion.value = row
  previewAnswer.value = ''
  previewAnswers.value = []
  previewVisible.value = true
}

// 处理删除题目
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
      type: 'warning'
    })
    const res = await request.delete(`/admin/questions/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchQuestions()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = { ...form.value, scaleId }
        let res
        if (dialogType.value === 'add') {
          res = await request.post('/admin/questions', data)
        } else {
          res = await request.put(`/admin/questions/${data.id}`, data)
        }
        
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchQuestions()
        } else {
          ElMessage.error(res.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

onMounted(() => {
  fetchScale()
  fetchQuestions()
})
</script>

<style scoped>
.scale-questions {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.scale-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.scale-info h3 {
  margin: 0;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.question-preview {
  padding: 20px;
}

.question-preview h4 {
  margin-top: 0;
  margin-bottom: 20px;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.score-info {
  display: flex;
  gap: 20px;
  margin-left: 20px;
  color: #606266;
}

.score-info span {
  font-size: 14px;
}
</style> 